<button type="button" class="layui-btn layui-btn-danger" onclick="createPaper()">创建试卷</button>
<table id="paper-info"></table>

<div id="create-paper" style="display: none;">
	<form class="layui-form" lay-filter="paper-form" id="paper-form">
		<div class="layui-form-item">
			<label class="layui-form-label">题量</label>
			<div class="layui-input-block">
				<input type="text" name="questionCount" class="layui-input">
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">每题分值</label>
			<div class="layui-input-block">
				<input type="text" name="scorePerQuestion" class="layui-input">
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">考试时长（分钟）</label>
			<div class="layui-input-block">
				<input type="text" name="examDuration" class="layui-input">
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">过期时间</label>
			<div class="layui-input-block">
				<input type="text" name="expire" id="expire" class="layui-input">
			</div>
		</div>
	</form>
</div>

<script>
	layui.use(["form", "table", "layer", "laydate"], function(form, table, layer, laydate) {
		//用户编号 全局变量
		var userId = parseInt(instance.defaults.userId);
		table.render({
			elem: '#paper-info',
			height: 460,
			url: serverPath + "/papers/" + userId,
			headers: {
				"auth-token": getToken()
			},
			//res 即为原始返回的数据
			parseData: function(res) {
				console.log("试卷管理表格原始返回的数据：");
				console.log(res);
				return {
					"code": res.data.code,
					"count": res.data.count,
					"data": res.data.data
				};
			},
			page: true,
			page: {
				limit: 5,
				limits: [5, 10, 15, 20]
			},
			cols: [
				[{
					field: '',
					title: '',
					align: "center",
					width: "5%",
					type: "checkbox"
				}, {
					field: 'paperId',
					title: '',
					align: "center",
					width: "1%",
					hide: true
				},
					{
						field: 'paperNo',
						title: '试卷编号',
						width: "13%",
						align: "center"
					}, {
					field: 'scorePerQuestion',
					title: '每题分值',
					width: "13%",
					align: "center"
				}, {
					field: 'questionCount',
					title: '题量',
					width: "13%",
					align: "center"
				}, {
					field: 'totalScore',
					title: '总分',
					width: "13%",
					align: "center"
				},
					{
						field: '',
						title: '操作',
						width: "45%",
						align: "center",
						templet: function(row) {
							return `
						    <button type="button" class="layui-btn layui-btn-normal" onclick="generatePaper(${row.paperId})">生成试卷</button>
                            <button type="button" class="layui-btn layui-btn-normal" onclick="preview(this)" status="${row.status}" paperId="${row.paperId}">预览</button>
                            <button type="button" class="layui-btn" onclick="paperDownload(this)" status="${row.status}" paperId="${row.paperId}" expire="${row.expire}">试卷下载</button>
                            <button type="button" class="layui-btn layui-btn-danger" onclick="deletePaper(${row.paperId})">删除</button>
                            <button type="button" class="layui-btn layui-btn-warm" onclick="cancel(this)" paperId="${row.paperId}" expire="${row.expire}">作废</button>
                            <button type="button" class="layui-btn layui-btn-normal" onclick="paperResult(${row.paperId})">考试统计结果下载</button>
                        `;
						}
					}
				]
			],
			done: function(res, curr, count) {
				if (curr > 1 && null == res.data) {
					curr = curr - 1;
					table.reload('paper-info', {
						//设定异步数据接口的额外参数，任意设
						where: {},
						page: {
							curr: curr
						}
					});
				}
			}
		});

		//创建试卷
		window.createPaper = function() {
			layer.open({
				type: 1,
				title: "创建试卷",
				area: ["500px", "350px"],
				content: $("#create-paper"),
				btn: ['确认', "取消"],
				btnAlign: 'c',
				yes: function(index, layero) {
					//获取表单中的输入所有的内容
					var createData = form.val("paper-form");
					//判断是否是数字之类的
					if (!/^[1-9]\d*$/.test(createData.questionCount)) {
						layer.alert("题目的数量为正整数...")
						return;
					}
					if (!/^[1-9]\d*$/.test(createData.scorePerQuestion)) {
						layer.alert("每题分值为正整数...")
						return;
					}
					if (!/^[1-9]\d*$/.test(createData.examDuration)) {
						layer.alert("考试时长（分钟）为正整数...")
						return;
					}
					if ("" == createData.expire) {
						layer.alert("到期时间不能为空...")
						return;
					}
					if (new Date(getCurDate(2)).getTime() > new Date(createData.expire).getTime()) {
						layer.alert("到期时间不能少于当前时间")
						return;
					}
					//发送axios请求创建问卷
					axios.post(serverPath + "/papers/" + userId, createData, {
						headers: {
							"auth-token": getToken()
						}
					}).then(function(response) {
						resetForm();
						table.reload("paper-info");
						layer.confirm(response.data.data, function() {
							layer.closeAll();
						})
					})
							.catch(function(error) {
								layer.alert(error.response.data.error)
							});
				},
				btn2: function(index, layero) {
					layer.confirm("是否退出?", function() {
						layer.closeAll();
					});
					return false;
				},
				success: function() {
					laydate.render({
						elem: '#expire',
						type: 'datetime',
						trigger: 'click'
					});
				}
			});
		};

		//生成试卷
		window.generatePaper = function(paperId) {
			axios.get(serverPath + "/papers/" + paperId, {
				params: {
					_generate: "_generate"
				},
				headers: {
					"auth-token": getToken()
				}
			}).then(function(response) {
				table.reload("paper-info");
				layer.confirm(response.data.data, function() {
					layer.closeAll();
				})
			})
					.catch(function(error) {
						layer.alert(error.response.data.error)
					});
		};

		//预览试卷
		window.preview = function(target) {
			var $target = $(target);
			var paperId = $target.attr("paperId");
			var status = $target.attr("status");
			if ("0" == status) {
				layer.alert("您还没有生成该试卷...");
				return;
			}
			location.href = "paper-view.html?paperId=" + paperId
		};

		//试卷下载
		window.paperDownload = function(target) {
			var $target = $(target);
			var paperId = $target.attr("paperId");
			var status = $target.attr("status");
			var expire = $target.attr("expire");
			if ("true" == expire) {
				layer.alert("当前试卷已过期，无法下载...");
				return;
			}
			if ("0" == status) {
				layer.alert("您还没有生成该试卷...");
				return;
			}
			if ("1" == status) {
				location.href = serverPath + "/download/" + paperId;
			}
		};
		// 试卷删除
		window.deletePaper = function(paperId) {
			layer.confirm("确定要删除吗？", function(index) {
				axios.delete(serverPath + "/papers/" + paperId, {
					headers: {
						"auth-token": getToken()
					}
				}).then(function(response) {
					layer.close(index);
					//刷新表格
					table.reload("paper-info");
					if (response.status == 204) {
						layer.confirm("删除试卷成功...", function() {
							layer.closeAll();
						})
					}
				}).catch(function(error) {
					layer.alert(error.response.data.error);
				});
			})
		};
		// 试卷作废
		window.cancel = function(target) {
			var $target = $(target);
			var paperId = $target.attr("paperId");
			var expire = $target.attr("expire");
			if ("true" == expire) {
				layer.alert("当前试卷已过期...");
				return;
			}
			if ("false" == expire) {
				axios.get(serverPath + "/papers/" + paperId, {
					params: {
						_cancel: "_cancel"
					},
					headers: {
						"auth-token": getToken()
					}
				}).then(function(response) {
					table.reload("paper-info");
					layer.confirm(response.data.data, function() {
						layer.closeAll();
					})
				})
						.catch(function(error) {
							layer.alert(error.response.data.error)
						});
			}
		};
		// 考试统计结果下载
		window.paperResult = function(paperId) {
			alert(paperId);
		};

		// 刚加载就隐藏的页面
		function pageOnload() {
			$("#create-paper").html(createPaperHtml());
		}

		//获取当前日期
		function getCurDate(format) {
			var _time = "";
			/**
			 * format=1表示获取年月日
			 * format=2表示获取年月日时分秒
			 * **/
			var now = new Date();
			var year = now.getFullYear();
			var month = now.getMonth() + 1;
			var date = now.getDate();
			var day = now.getDay(); //得到周几
			var hour = now.getHours(); //得到小时
			var minu = now.getMinutes(); //得到分钟
			var sec = now.getSeconds(); //得到秒
			if (format == 1) {
				_time = year + "-" + month + "-" + date
			} else if (format == 2) {
				_time = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec
			}
			return _time
		}
		//重置表单
		function resetForm() {
			document.getElementById("paper-form").reset();
		}
	})

</script>